package service

import (
	"crypto/tls"
	"jslog/example"
	"jslog/util"
	"net/smtp"

	"github.com/jordan-wright/email"
	gomail "gopkg.in/mail.v2"
)

type Mail struct {
	Base
	Smtp     string
	Port     string
	Authcode string
	From     string
}

// 发送多发(单发接收者为1)
func (s Mail) GroupSend(to []string, title string, content string) (string, error) {

	e := email.NewEmail()
	e.To = to
	e.From = example.JSLOG_CONF.Email.From
	e.Subject = title
	e.HTML = []byte(content)

	auth := smtp.PlainAuth("", example.JSLOG_CONF.Email.From, example.JSLOG_CONF.Email.Secret, example.JSLOG_CONF.Email.Host)
	err := e.SendWithTLS(example.JSLOG_CONF.Email.Host+":"+util.IntToStr(example.JSLOG_CONF.Email.Port), auth, &tls.Config{ServerName: example.JSLOG_CONF.Email.Host})
	if err != nil {
		return "", err
	}
	return "success", nil
}

// 邮件-单发
func (s Mail) Send(to string, title string, content string) (string, error) {

	m := gomail.NewMessage()
	m.SetHeader("From", example.JSLOG_CONF.Email.From)
	m.SetHeader("To", to)
	m.SetHeader("Subject", title)
	m.SetBody("text/plain", content)
	d := gomail.NewDialer(example.JSLOG_CONF.Email.Host, example.JSLOG_CONF.Email.Port, example.JSLOG_CONF.Email.From, example.JSLOG_CONF.Email.Secret)
	d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
	if err := d.DialAndSend(m); err != nil {
		return "error", err
	}
	return "success1", nil
}
